<template>
  <!-- 线索上报 -- 新增 -->
  <view class="clueAddition">
    <view class="wrapper">
      <view class="wrapper-item content">
        <u-form :model="form" ref="form" label-width="200" labelPosition="top" :error-type="errorType">

          <u-form-item label="本次关怀JS障碍人员：" :borderBottom="false" :required="true">
            <u--input v-model.trim="form.clueTitle" disabled border="none" placeholder="请填写" :maxlength="30"></u--input>
          </u-form-item>

          <u-form-item label="关怀时间" :borderBottom="false" :required="true" @click="cellTimeClick()">
            <u--input v-model="form.helpTime" disabled disabledColor="#ffffff" placeholder="请选择"
              border="none"></u--input>
            <image :src="baseImgUrl + 'day-icon2.png'" mode="" slot="right" class="seleTime"></image>
          </u-form-item>

          <u-form-item label="关怀地点" :borderBottom="false" :required="true">
            <view class="map-form">
              <u--input v-model="form.helpAddress" border="none" placeholder="在地图上选择地点" :maxlength="30"
                :readonly="true"></u--input>
              <view class="map-img" @click="mapHandle">
                <image :src="baseImgUrl + 'map-icon2.png'" mode="aspectFill"></image>
              </view>
            </view>
          </u-form-item>
          <view style="padding-top: 20rpx"></view>
          <view class="forTitle">
            <view> <text class="forReq">*</text>关怀描述 </view>
          </view>
          <view class="text-AreaView">
            <u--textarea v-model="form.helpDescribe" placeholder="请用简洁的文字描述本次对该人员的关怀过程" count maxlength="300"
              height="135"></u--textarea>
          </view>

          <!-- 录音 -->
          <view style="padding-top: 20rpx"></view>
          <view class="forTitle">
            <view>音频信息</view>
            <view class="state">（上传大小不超过30M本地音频文件）</view>
          </view>
          <view class="media-wrapper" v-if="!audioSrc">
            <nb-voice-record @startRecord="start" @endRecord="end" @cancelRecord="cancel" :btnStyle="{width: '200rpx',height: '160rpx', 
            'background': `url(${baseImgUrl}add-sound-recording.png)`,
            'background-size': 'cover',
            'background-repeat': 'no-repeat', 
            'background-position': 'center'
            }" btnDefaultText=" "></nb-voice-record>

            <view class="upload-file" @click="showAudioModel = true">
            </view>
          </view>

          <!-- <view class="choose-file-style">

          </view> -->
          <view class="audio-wrapper" v-if="audioSrc">
            <view class="left-i">
              <image v-if="play == false" class="start-img" :src="baseImgUrl + 'audio-start.png'" @click="playAudio">
              </image>
              <image v-else class="pause-img" :src="baseImgUrl + 'audio-pause.png'" @click="pauseAudio"></image>
            </view>
            <view class="right-i">
              <div class="a-item">
                <div class="a-item-left">
                  <div class="audio-text">音频信息</div>
                  <div class="audio-size">{{ formatBytes(fileSize) }}</div>
                </div>
                <div class="a-item-right text-delete" @click="handleDelete">
                  移除
                </div>
              </div>
              <div class="a-item">
                <div class="a-item-time">
                  <div>{{ formatMilliseconds(current) }}</div>
                  <div>{{ formatMilliseconds(duration) }}</div>
                </div>
              </div>
              <div style="padding-top: 12rpx">
                <u-line-progress :percentage="percentage" activeColor="#2488F5" :height="8" :showText="false" />
              </div>
            </view>
          </view>
          <!-- 录音结束 -->
          <view style="padding-top: 20rpx"></view>
          <view class="forTitle">
            <view>图片信息</view>
            <view class="state">（最多可上传3张图片，非必填）</view>
          </view>
          <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="3"
            :multiple="true" width="96" height="80">
            <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
          </u-upload>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn">
      <button class="cancel-btn lt" type="primary" @click="navBack()">
        取消
      </button>
      <button class="submit-btn" type="primary" @click="submitHandle">
        提交
      </button>
    </view>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="datetime"
      :formatter="formatter" :minDate="minDate" :maxDate="maxDate" @close="datetimeShow = false"
      @cancel="datetimeShow = false" @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>

    <u-picker :show="pickerShow" :columns="columns" :keyName="keyName" @confirm="showConfirm"
      @close="pickerShow = false" @cancel="pickerShow = false" :closeOnClickOverlay="true"></u-picker>

    <u-action-sheet @select="handleSelectAudio" :actions="uploadAudioTypes" :round="8" cancelText="取消"
      :show="showAudioModel" @close="showAudioModel = false"></u-action-sheet>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    clueReportingSave
  } from "@/api/home.js";
  import {
    addWbHelpInfoRecords,
    ajaxGetDictItems
  } from "@/api/api.js";
  import {
    Toast,
    navBack,
    handleClickRouter,
    uniTrim,
    pvwImage,
    useNetWork,
    isLoading,
    formatters,
    dayTurnTime,
    getHeader,
    formatMilliseconds,
    formatBytes,
    uploadFile,
    parseJson,
    getOptionsParams,
  } from "@/utils/util.js";
  import moment from "@/utils/moment.js";
  import mixin from "@/utils/mixin.js";

  export default {
    name: "clueAddition",
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        role: uni.getStorageSync('role'),

        form: {
          helpPic: '',
          helpVideo: '',
          helpDescribe: '',
          helpTime: '',
          helpAddress: '',
          log: '',
          lat: ''
        },
        errorType: ["none"],

        lnglat: "",
        clueDescription: "",
        fileList: [],
        clueImagesUrlList: [],
        fileNum: 0, // 记录长传图片张数

        keyName: "text",

        // 录音
        play: false,
        // 百分比
        percentage: 0,
        // 实例化音频组件
        audioContext: null,
        // 总时长
        duration: 0,
        // 文件大小
        fileSize: 0,
        // 当前播放时间
        current: 0,
        audioSrc: null,

        uploadAudioTypes: [{
            name: '选择微信文件'
          },
          // {
          //   name: '选择手机录音文件'
          // }
        ],
        showAudioModel: false,
        routerParams: {}
      };
    },
    onLoad(options) {
      this.options = options;
      this.form.discoveryTimeName = moment().format("YYYY/MM/DD HH:mm");
      this.form.discoveryTime = moment().valueOf();
      this.routerParams = getOptionsParams(options)
      this.$set(this.form, 'mentalPatientId', this.routerParams.id)
      this.$set(this.form, 'clueTitle', this.routerParams.name)
    },
    onReady() {
      this.initAudio();
    },
    onShow() {

    },
    onUnload() {
      uni.$off("leadPoliceStation");
    },
    methods: {
      handleClickRouter,
      navBack,
      pvwImage,
      moment,
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick() {
        this.maxDate = +new Date();
        this.timeValue = this.maxDate;
        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },

      showTimeConfirm(e) {
        if (e.value) {
          this.form.helpTime = formatters(e.value, "YY/MM/DD HH:mm");
          // this.form.helpTime = dayTurnTime(this.form.discoveryTimeName);
        }
        this.datetimeShow = false;
      },

      mapHandle() {
        uni.chooseLocation({
          success: (res) => {
            let {
              longitude,
              latitude,
              address
            } = res;
            this.form.log = longitude;
            this.form.lat = latitude;
            this.form.helpAddress = address;
          },
          fail: (err) => {
            console.log(err, "错误的");
          },
        });
      },

      policeAgencyFoces() {
        if (!this.form.discoverySite) {
          Toast("请先选择发现地点");
          return;
        }

        uni.navigateTo({
          url: `/leadReporting/leadReporting/leadPoliceStation?lng=${this.form.lng}&lat=${this.form.lat}`,
        });
      },

      afterRead(info) {
        useNetWork(); // 判断是否有网络
        isLoading();

        let _this = this;
        _this.fileNum += info.file.length;
        for (let v of info.file) {
          uploadFile({
              url: "/web/sys/upload/upload_file",
              filePath: v.url,
              name: "file",
              formData: {
                type: 83,
              },
            })
            .then((res) => {
              let {
                fullPath,
                halfPath
              } = res.result;
              this.fileList.push({
                url: fullPath,
              });
              this.clueImagesUrlList.push(halfPath);
              if (this.clueImagesUrlList.length == this.fileNum) {
                isLoading(false);
              }
            })
            .finally(() => {
              isLoading(false);
            })
        }
      },
      deletePic(e) {
        this.fileList.splice(e.index, 1);
        this.clueImagesUrlList.splice(e.index, 1);
        this.fileNum -= 1;
      },

      /* cell 点击 */
      async cellClick() {
        let {
          result: clue_type
        } = await ajaxGetDictItems({
          code: "clue_type",
        });
        this.columns[0] = clue_type;
        this.pickerShow = true;
      },
      /* 选择器 确定 */
      showConfirm(e) {
        let arr = e.value[0];
        this.form.clueType = arr.value;
        this.form.clueType_dict = arr.title;
        this.pickerShow = false;
      },

      async submitHandle() {
        let {
          mentalPatientId,
          helpTime,
          helpAddress,
          helpDescribe
        } = this.form;

        if (!mentalPatientId) {
          Toast("请选择关怀人员！");
          return;
        }

        if (!helpTime) {
          Toast("请选择关怀时间");
          return;
        }

        if (!this.form.log) {
          Toast("请选择关怀地点");
          return;
        }

        if (!helpDescribe) {
          Toast("请输入关怀描述！");
          return;
        }


        this.form.clueDescription = this.clueDescription;
        this.form.helpPic = this.clueImagesUrlList.join(',');
        let fileRes, fullPath,
          halfPath
        if (this.audioSrc) {
          fileRes = await uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: this.audioSrc, // 要上传的文件路径
            name: "file", // 上传文件对应的 key 值
            formData: {
              type: 84,
            },
          })
          fullPath = fileRes.result.fullPath;
          halfPath = fileRes.result.halfPath;
        }
        let data = {
          ...this.form,
        }
        if (halfPath) {
          data.helpVideo = halfPath
        }

        let res = await addWbHelpInfoRecords(data);
        if (res.code == 200) {
          Toast("保存成功");
          uni.setStorageSync("leadReporting", true);
          uni.$emit('addOk')
          navBack();
          return;
        }
        Toast(res.message);
      },

      // 初始化 音频
      initAudio() {
        this.audioContext = uni.createInnerAudioContext();
        this.audioContext.onPlay(() => {});
        this.audioContext.onError((err) => {
          console.log(err);
        });
        this.audioContext.onEnded(() => {
          console.log("播放结束");
          this.percentage = 100;
          this.current = 0;
          this.play = false;
        });
        this.audioContext.onTimeUpdate(() => {
          this.current = this.audioContext.currentTime * 1000;
          if (!this.duration) {
            this.duration = this.audioContext.duration;
          }
          if (this.duration > 0) {
            if (this.current === this.duration) {
              this.percentage = 100;
              return;
            }
            // this.percentage = parseInt(((parseInt(value) / parseInt(this.duration)) * 100).toFixed(2))
            // 计算百分数，也就是进度条的长度
            this.percentage = Number(
              ((this.current / this.duration) * 100).toFixed(4)
            );
          }
        });
      },
      formatMilliseconds,
      formatBytes,
      start() {
        // 开始录音
      },
      end(event) {
        // 检测大小大于 30m 则返回
        if (event.fileSize > 31457280) {
          Toast('音频文件不能大于30M！')
          return
        }
        // 结束录音并处理得到的录音文件
        // event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段
        // 录音结束之后给 音频组件赋值
        this.audioContext.src = event.tempFilePath;
        this.audioSrc = event.tempFilePath;
        this.duration = event.duration;
        this.fileSize = event.fileSize;
        this.current = 0;
        this.percentage = 0;
      },
      cancel() {
        // 用户取消录音
      },

      // 播放音频
      playAudio() {
        this.play = true;
        this.percentage = 0;
        this.audioContext.play();
      },
      pauseAudio() {
        this.play = false;
        this.audioContext.pause();
      },
      reset() {
        this.audioContext.src = null;
        this.audioSrc = null;
        this.duration = 0;
        this.fileSize = 0;
      },
      handleDelete() {
        this.reset();
      },
      handleSelectAudio(event) {
        const {
          name
        } = event

        wx.chooseMessageFile({
          count: 1,
          type: 'file',
          extension: ['.m4a', '.mp3', 'm4a', 'mp3'],
          success: (res) => {
            const firstFile = res.tempFiles[0]
            const {
              size,
              path,
              time
            } = firstFile

            if (size > 31457280) {
              Toast('音频文件不能大于30M！')
              return
            }

            this.audioContext.src = path;
            this.audioSrc = path;
            this.fileSize = size;
            this.current = 0;
            this.percentage = 0;
            wx.getVideoInfo({
              src: path,
              success: (res) => {
                console.log(res)
                const {
                  duration
                } = res
                this.duration = duration * 1000
              }
            })
          }
        })

        this.showAudioModel = false
      }
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  @import '../styles/sound-recording.scss';

  .clueAddition {
    flex: 1;
    background-color: #f3f3f3;

    .clueAddition-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 30rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 710rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }

      /deep/.u-form-item__body__right__content {
        padding: 12rpx 18rpx;
        border-radius: 8rrpx;
        background: #f9f9f9;
      }

      /deep/.u-input__content {
        background: #f9f9f9;
      }

      .seleTime {
        width: 30rpx;
        height: 30rpx;
      }

      .forTitle {
        display: flex;
        position: relative;
        margin-bottom: 15rpx;
        font-size: 30rpx;

        .forReq {
          position: absolute;
          left: -9px;
          color: #f56c6c;
          line-height: 20px;
          font-size: 20px;
          top: 3px;
        }

        .state {
          color: #a1a1a1;
          font-size: 26rpx;
        }
      }

      .text-AreaView {

        /deep/.u-textarea,
        .u-textarea__count {
          background-color: #f9f9f9 !important;
        }

        .u-textarea__field {
          font-weight: 400;
        }

        /deep/ .input-placeholder {
          font-weight: 400;
        }
      }
    }

    .map-form {
      display: flex;

      .map-img {
        color: #2488f5;
        font-size: 30rpx;
        font-weight: 500;

        image {
          display: inline-block;
          margin-right: 10rpx;
          vertical-align: text-bottom;
          width: 35rpx;
          height: 35rpx;
        }
      }
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }

    .choose-file-style {
      background: url($baseImgUrl + "add-audio.png");
      width: 200rpx;
      height: 160rpx;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
    }

    .media-wrapper {
      display: flex;
    }

    .upload-file {
      background: url($baseImgUrl +'add-audio.png');
      width: 200rpx;
      height: 160rpx;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      margin-left: 30rpx;
    }
  }
</style>